package com.cq.hd.gateway.utils;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;

public class RequestAddParameterUtils {

    public static ServerHttpRequest addParameter(ServerWebExchange exchange, String paraName, String paraValue) {
        URI uri = exchange.getRequest().getURI();
        StringBuilder query = new StringBuilder();
        String originalRawQuery = uri.getRawQuery();
        if (StringUtils.hasText(originalRawQuery)) {
            query.append(originalRawQuery);
            if (originalRawQuery.charAt(originalRawQuery.length() - 1) != '&') {
                query.append('&');
            }
        }

        query.append(paraName);
        query.append('=');
        query.append(paraValue);

        URI newUri = UriComponentsBuilder.fromUri(uri).replaceQuery(query.toString()).build(true).toUri();
        return exchange.getRequest().mutate().uri(newUri).build();
    }

}
